package polimi.sc.expoquest.screen.singleplay;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Random;

import polimi.sc.expoquest.QuestApplication;
import polimi.sc.expoquest.R;
import polimi.sc.expoquest.storage.datasources.PlayedGameDataSource;
import polimi.sc.expoquest.storage.datasources.SingleGameDataSource;
import polimi.sc.expoquest.storage.datasources.TagDataSource;
import polimi.sc.expoquest.storage.model.PlayedGame;
import polimi.sc.expoquest.storage.model.SingleGame;
import polimi.sc.expoquest.storage.model.Tag;
import polimi.sc.expoquest.screen.CameraActivity;
import polimi.sc.expoquest.screen.DashboardActivity;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.view.Menu;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.RatingBar;
import android.widget.Toast;

public class SingleplayCameraActivity extends Activity {	
	//----------------
	// Attributes
	//----------------
	//The regex for splitting the tags capture on the user interface
	public static final String TAGS_REGEX =",";
	//The single game datasource
	private SingleGameDataSource singleGameDS;
	//The tag datasource
	private TagDataSource tagDS;
	//The played game datasource
	private PlayedGameDataSource playedGameDS;
	//The camera game selected
	private SingleGame cameraGame;
	//The max poing
	private int maxpoint;
	public static final int CAMERA_CODE = 99;
	private String fileName;
	@Override	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_singleplay_camera);
		//Disable the star rating cliking
		RatingBar barStatus = (RatingBar)findViewById(R.id.ratingBarExpo);
		barStatus.setEnabled(false);		
		//1. Choosing randomly a trivia game
		cameraGame = getRandomCameraGame();
		if(cameraGame!= null)
		{
			//2. Showing the game description
			TextView gameDescription = (TextView)findViewById(R.id.game_desc);
			String desc= cameraGame.getDescription();
			gameDescription.setText(desc);
			//3. getting the maxpoint
			maxpoint = cameraGame.getMaxPoints();
		}	
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_singleplay_camera, menu);
		return true;
	}
	/**
	 * Submitting the tags to the game
	 * @param v
	 */
	public void submitBtnPressed(View v)
	{	
		insertPlayedGame();
	}
	/**
	 * When taking the picture in the game
	 * @param v
	 */
	public void takepicturePressed(View v)
	{
		Intent cameraIntent = new Intent(this, CameraActivity.class);		
		startActivityForResult(cameraIntent, CAMERA_CODE);
	}
	/**
	 * When the roll button is pressed again
	 * @param v
	 */
	public void rollBtnPressed(View v)
	{
		Random generator = new Random();		
		int random = generator.nextInt(3); // find a random number between 0,1,2		
		if (random == 0)
		{
			Intent dashbordIntent = new Intent(this, SingleplayTriviaActivity.class);
	        startActivity(dashbordIntent);
		}
		else if (random == 1)
		{
			Intent dashbordIntent = new Intent(this, SingleplayCommentActivity.class);
	        startActivity(dashbordIntent);
		}
		else if (random == 2)
		{
			Intent dashbordIntent = new Intent(this, SingleplayCameraActivity.class);
	        startActivity(dashbordIntent);
		}
	}
	/**
	 * Going back to the dashboard screen
	 * @param v
	 */
	public void homepagebtn_click(View v){
		Intent dashbordIntent = new Intent(this, DashboardActivity.class);
        startActivity(dashbordIntent);
	}
	//--------------------
	// Auxiliar methods
	//--------------------
	/**
	 * Returns a trivia game randomly chosen among the available in the system
	 * @return
	 */
	private SingleGame getRandomCameraGame()
	{
		//1. Creating the data source if it is not created already	
		if(singleGameDS== null)
			singleGameDS = new SingleGameDataSource(this);
		//1.1 opening the data source
		singleGameDS.open();
		//2. Obtaining the view of the results of the rolling
		Collection<SingleGame> cameraGames = singleGameDS.getSingleGameByType(SingleGame.TYPE_CAMERA);
		//3. Closing the database connection
		singleGameDS.close();
		//4. Choosing one comment randomly
		Random generator = new Random();
		//4.1 getting the total trivias available in the 
		int totalCamera = cameraGames.size();
		//4.2 We choose one index randomly
		int random=0;
		SingleGame g = null;
		try {
			random = generator.nextInt(totalCamera);
			//4.3 we retrieve the game in the index selected
			Object [] o = cameraGames.toArray();
			g = (SingleGame)o[random];
		}
		catch(IllegalArgumentException e){
		}
		return g;
		
	}
	/**
	 * Insert the camera played game into the database
	 */
	public void insertPlayedGame()
	{
		//1. Inserting the tags in the database
		//1.1 Getting the inserted tags by the user
  		EditText tet= (EditText)findViewById(R.id.tagtext);
  		//1.2 Splitting the string
  		//TODO do validation of commas
  		String tagsStr = tet.getText().toString();
  		String[] tags = tagsStr.split(TAGS_REGEX);
  		//1.3 Inserting the tags into the database
  		Collection<Integer> tagIDs = insertTags(tags);
		//2. Assigning the points gained
		Random generator = new Random();
		int points = generator.nextInt(cameraGame.getMaxPoints());
		//3.Retrieving the picture taken with the camera
		//TODO use the camera API for getting such file
		String picURI = cameraGame.getPicURI();
		if(playedGameDS == null)
			playedGameDS = new PlayedGameDataSource(this);	
		playedGameDS.open();		
		//4. Retrieving the user ID logged into the application
		QuestApplication questApp = (QuestApplication)getApplicationContext();
		int userID = questApp.getUserID();
		//5. Saving the played game in the database
		PlayedGame pl =  playedGameDS.insertPlayedCamera(picURI, points, userID, cameraGame.getId(), tagIDs);
		playedGameDS.close();
		//6. Showing the success of the insertion
		String gameSubmission= "Data of the play game inserted:\n" + " id: " + pl.getId()+ "\n picture: "+ pl.getPicURI()+ "\n points "+ pl.getPoints(); 
		Toast toast = Toast.makeText(this, gameSubmission , Toast.LENGTH_LONG);
		toast.show();
		//7.Giving the points to the user
		RatingBar bar = (RatingBar)findViewById(R.id.ratingBarExpo);
		bar.setRating(maxpoint/5);
	}
	
	/**
	 * Insert the tags given to the database
	 * @param tags
	 * @return
	 */
	public  Collection<Integer> insertTags(String[] tags)
	{
		//1. Creating the collection
		Collection<Integer> tagsIDs = new ArrayList<Integer>();
		//2. Creating the datasource
		if(tagDS == null)
			tagDS = new TagDataSource(this);
		//3. Inserting the tags
		tagDS.open();
		int size = tags.length;
		for(int i=0; i<size; i++)
		{
			String tag = tags[i];
			//Check if the tag already exists on the database, if so, get the ID
			int id = tagDS.getTagID(tag);
			//Non existing tag (at least spelled as the tag given
			if(id== TagDataSource.NO_ID_FOR_TAG)
			{
				Tag t=tagDS.insert(tag);
				id = t.getId();
				
			}
			tagsIDs.add(id);
			
		}
		return tagsIDs;
	}

	@Override
	public void onActivityResult(int requestCode , int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);
			if (requestCode == CAMERA_CODE)
			{
				if (resultCode == Activity.RESULT_OK)
				{	
					fileName = data.getStringExtra("fileName");
					File f = new File(fileName);	
					Toast.makeText(this, fileName, Toast.LENGTH_LONG).show();
					
					try {
						InputStream ims = new FileInputStream(f);
						Drawable d = Drawable.createFromStream(ims, null);
						ImageView imgpic = (ImageView) findViewById(R.id.picframe);
						imgpic.setVisibility(View.VISIBLE);
						imgpic.setImageDrawable(d);
						ImageButton imgCamera = (ImageButton) findViewById(R.id.takepicbutton);
						imgCamera.setVisibility(View.INVISIBLE);
					} catch (FileNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}				
			}
			
	}


	
}
